import axios from 'axios'

class Post {
  constructor (baseUrl = baseURL) {
    this.baseUrl = baseUrl
    this.queue = {}
  }
  getInsideConfig () {
    const config = {
      baseURL: this.baseUrl,
      headers: {
        'Content-Type': 'application/json;charset=utf-8'
      },
      method:'post',
    }
    return config
  }
  destroy (url) {
    delete this.queue[url]
  }
  interceptors (instance, url) {
    // 请求拦截
    instance.interceptors.request.use(config => {
      this.queue[url] = true
      return config
    }, error => {
      return Promise.reject(error)
    })

    // 响应拦截
    instance.interceptors.response.use(config => {
      var data = config.data;
      var status = config.status;
      this.destroy(url)
      if(status != 200){
        Notice.error('网路错误');
      }
      if(data.code !== '000000'){
        if(data.code == '000001'){
          if(window.vm){
            window.vm.$Modal.info({
              title:'请登录',
              footerHide:true,
              closable:true,
              render: h =>  {
                var t = h('login',{
                  class:'login-all-post',
                  props:{
                    queue:config
                  },
                })
                //window.vm._update(t,true);
                return t;
              }
            })
            window.vm.$nextTick(()=>{
              let loginnode = document.getElementsByClassName ('login-all-post');
              loginnode[0].parentNode.nextSibling.style.display = 'none';
            })
          }
        }
        return Promise.reject(data.msg,data.code,data.id);
      }
      return data.data;
    }, error => {
      this.destroy(url)
      return Promise.reject(error)
    })
  }
  request (options) {
    const instance = axios.create({
      withCredentials:true
    })
    options = Object.assign(this.getInsideConfig(), options)
    this.interceptors(instance, options.url)
    return instance(options)
  }
}
export default Post
